from pyvisml import VisML

print('Creating an empty tree')
t = VisML.create_empty_visml_tree()

print('Adding three nodes')
nodes = {}
names = ['NODE1', 'NODE2', 'NODE3']

for name in names:
    nodes[name] = t.add_node(name, '0', '0')

for name in names:
    assert name in [ node.name for node in t.nodes ]

print('Adding two metanodes')
metanodes = {}
names = ['METANODE1', 'METANODE2']

for name in names:
    metanodes[name] = t.add_metanode(name, '0', '0')

print('Moving nodes to metanodes')
t.add_node_to_metanode(nodes['NODE2'], metanodes['METANODE1'], duplicate=True)
t.add_node_to_metanode(nodes['NODE2'], metanodes['METANODE2'], duplicate=True)
t.add_node_to_metanode(nodes['NODE3'], metanodes['METANODE2'], duplicate=True)

assert 'NODE2' in metanodes['METANODE1'].children
assert nodes['NODE2'].duplicates
assert not nodes['NODE1'].duplicates and not nodes['NODE3'].duplicates

print('Overlapping metanodes')
t.add_node_to_metanode(metanodes['METANODE1'], metanodes['METANODE2'])

assert 'METANODE1' in metanodes['METANODE2'].children
assert metanodes['METANODE1'].groups == ['METANODE2']

print('Linking nodes')
t.add_edge(nodes['NODE1'], nodes['NODE2'])

assert t.isconnected(nodes['NODE1'], nodes['NODE2'])
assert len(t.edges) == 1
assert t.edges[0].to in ('NODE1', 'NODE2')
assert nodes['NODE1'].links[0].to == 'NODE2'
assert nodes['NODE2'].links[0].to == 'NODE1'

print('Linking duplicates')
dup = nodes['NODE2'].duplicates[0]
t.add_edge(dup, nodes['NODE3'])
t.add_edge(dup, metanodes['METANODE2'])

assert dup.uid in [ x.to for x in t.edges ] or dup.uid in [ x.linkFrom for x in t.edges ]
assert len(nodes['NODE3'].links) == 1
link = nodes['NODE3'].links[0]
assert link.toDup == dup.uid
assert link.to == dup.parent.name
assert len(dup.parent.links) == 3
link = [ x for x in dup.parent.links if x.fromDup == dup.uid ][0]
assert link.to == nodes['NODE3'].name
assert len(metanodes['METANODE2'].links) == 1

print('Removing nodes')
t.remove_node(nodes['NODE2'])

assert len(nodes['NODE3'].links) == 0
assert len(nodes['NODE1'].links) == 0
assert len(t.edges) == 0
assert len(metanodes['METANODE2'].links) == 0
